//
//  HomeViewController.m
//  SunXi
//
//  Created by dllo on 15/11/26.
//  Copyright © 2015年 大远. All rights reserved.
//

#import "HomeViewController.h"

@interface HomeViewController ()<UITableViewDataSource, UITableViewDelegate, DyScrollViewdelegate>
@property(nonatomic, retain) NSMutableArray *scrollArr;
@property(nonatomic, retain) NSMutableArray *dataArr;
@property(nonatomic, assign) NSInteger page;
@property(nonatomic, retain) MBProgressHUD *hud;
@property(nonatomic, retain) UITableView *tableView;

@property(nonatomic, retain) DyScrollView *scrollView;


@end

@implementation HomeViewController
- (void)dealloc
{
    /*
     
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addRightButtonItem) name:@"已登录" object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addRightButtonItem) name:@"自动登录" object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushWeb:) name:@"网页推送" object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateload) name:@"退出登录" object:nil];
     */
    
        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"已登录" object:nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"自动登录" object:nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"退出登录" object:nil];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // 下面的bar不显示
    self.navigationController.navigationBar.translucent = NO;
    self.dataArr = [NSMutableArray array];
    self.page = 0;
    self.navigationItem.title = @"首页";
    
    self.tableView = [[UITableView alloc] init];
    [SV addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(SV).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
        
    }];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    // 横杆去掉
    self.tableView.separatorStyle = NO;
    //计算轮播图的高度
    CGFloat hei = 300 * WIDTH / 640;
    
    self.scrollView = [[DyScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, hei)];
    self.tableView.tableHeaderView = _scrollView;
    _scrollView.delegate = self;
    
    [ShowMytext showHUDloadView:SV];
    [self create];
    //MARK: 上拉刷新下拉加载
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        [self create];
        [self.tableView reloadData];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page++;
        [self loadHomeData];
    }];
    if ([UserModel shareSingleton].userName.length > 0) {
        [self addRightButtonItem];
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addRightButtonItem) name:@"已登录" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addRightButtonItem) name:@"自动登录" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateload) name:@"退出登录" object:nil];
 
}
- (void)updateload{
    self.navigationItem.rightBarButtonItem = nil;
}



//MARK:轮播图的点击方法
- (void)takeValue:(NSInteger)TouchValue {
    NSString *touchv = (NSString *)[self.scrollArr[TouchValue] url];
    NSLog(@"%@",touchv);
    NSArray *valueArr = [touchv componentsSeparatedByString:@"/"];
    if ([touchv containsString:@"article"] ) {
        NSLog(@"%@",[valueArr lastObject]);
        [self loadarticle:[valueArr lastObject]];
    }else if ([touchv containsString:@"fm"]){
        [self loadFm:[valueArr lastObject]];
    }else if ([touchv containsString:@"http"]){
        WebView *web = [[WebView alloc]init];
        web.url = touchv;
        [self.navigationController pushViewController:web animated:YES];

    }
    
}

//加载轮播图pianke页面
- (void)loadarticle:(NSString *)value{
    [ShowMytext showHUDloadView:SV];
    NSString *url = @"http://api2.pianke.me/article/info";
    NSDictionary *para = @{@"contentid":value,@"client":@"2"};
    [DyAFnetWorking POSTAfnNetworkingWithUrl:url WithParameters:para Block:^(id result) {
        WebView *web = [[WebView alloc]init];
        web.html = NO;
        //"shareinfo"
        web.tittle  =result[@"data"][@"shareinfo"][@"title"];
        web.url = result[@"data"][@"shareinfo"][@"url"];
        [self.navigationController pushViewController:web animated:YES];
        [ShowMytext hiddHUDloadView];
    }];
}
//首页调转电台方法
- (void)loadFm:(NSString *)value{
    RadiolistViewController *listVC = [[RadiolistViewController alloc]init];
    RadioModel *model = [[RadioModel alloc]init];
    model.radioid = value;
    listVC.radioid = model.radioid;
    listVC.title = @"加载中...";
    [self.navigationController pushViewController:listVC animated:YES];
}
//MARK: 数据解析
- (void)create{
    NSString *homePageUrl = @"http://api2.pianke.me/pub/today";
    NSString *body = @"start=0&client=2&limit=10";
    [DyAFnetWorking cachePostWithURL:homePageUrl WithbodyStr:body success:^(id result) {
        
        //  轮播图数组处理
        self.scrollArr = [ScrollPicModel baseModelByArr:result[@"data"][@"carousel"]];
        NSInteger p = self.scrollArr.count;
        for (NSInteger i = 0; i < p; i++) {
            ScrollPicModel *model = self.scrollArr[i];
            if ([model.url containsString:@"pianke://topic"]){
                [self.scrollArr removeObjectAtIndex:i];
                i--;
                p--;
            }else if ([model.url containsString:@"pianke://timeline"]){
                [self.scrollArr removeObjectAtIndex:i];
                i--;
                p--;
            }
        }
        
        NSMutableArray *arr = [NSMutableArray array];
        for (ScrollPicModel *temp in _scrollArr) {
            NSString *url = temp.img;
            [arr addObject:url];
        }
        [_scrollView createView:arr width:WIDTH];
        
        //  首页cell数组处理
        self.dataArr = [DataModel baseModelByArr:result[@"data"][@"list"]];
        
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [ShowMytext hiddHUDloadView];
        
    } failure:^(id nonet) {
        
        NSLog(@"%@",nonet);
        
    }];
    
}

//MARK: 数据解析
- (void)loadHomeData{
    NSString *homePageUrl = @"http://api2.pianke.me/pub/today";
    NSString *para = [NSString stringWithFormat:@"start=%ld&client=2&limit=10",(self.page * 10)];
   
    [DyAFnetWorking cachePostWithURL:homePageUrl WithbodyStr:para success:^(id result) {
        self.dataArr = [DataModel baseMedelByArr:self.dataArr addArr:[DataModel baseModelByArr:result[@"data"][@"list"]]];
        [ShowMytext hiddHUDloadView];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
    } failure:^(id nonet) {
        
        
    }];
    

}

//MARK: tableView 高度
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([[self.dataArr[indexPath.row] Type] isEqualToNumber:@1] || [[self.dataArr[indexPath.row] Type] isEqualToNumber:@6] || [[self.dataArr[indexPath.row] Type] isEqualToNumber:@9] || [[self.dataArr[indexPath.row] Type] isEqualToNumber:@14] || [[self.dataArr[indexPath.row] Type] isEqualToNumber:@18]) {
        return HEIGHT / 667 * 500;
    }else if ([[self.dataArr[indexPath.row] Type] isEqualToNumber:@2])  {
        
        
        return HEIGHT / 667 * 400;
    }else if ([[self.dataArr[indexPath.row] Type] isEqualToNumber:@3] || [[self.dataArr[indexPath.row] Type] isEqualToNumber:@7] || [[self.dataArr[indexPath.row] Type] isEqualToNumber:@11] || [[self.dataArr[indexPath.row] Type] isEqualToNumber:@27] || [[self.dataArr[indexPath.row] Type] isEqualToNumber:@29])  {
        
        return HEIGHT / 667 * 400;
    } else if ([[self.dataArr[indexPath.row] Type] isEqualToNumber:@5]) {
        
        return HEIGHT / 667 * 350;
    }else {
        return HEIGHT / 667 * 400;
    }

    
}
//MARK: tableView个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

//MARK: UITableViewCell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([[self.dataArr[indexPath.row] Type] isEqualToNumber:@1] || [[self.dataArr[indexPath.row] Type] isEqualToNumber:@6] || [[self.dataArr[indexPath.row] Type] isEqualToNumber:@9] || [[self.dataArr[indexPath.row] Type] isEqualToNumber:@14] || [[self.dataArr[indexPath.row] Type] isEqualToNumber:@18]) {
        
        static NSString *reuse = @"reuse";
        PsychologyCell *psyCell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!psyCell) {
            psyCell = [[PsychologyCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse];
        }
        DataModel *model = self.dataArr[indexPath.row];
        psyCell.model = model;
        psyCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return psyCell;
        
    }else if ([[self.dataArr[indexPath.row] Type] isEqualToNumber:@2]) {
        
        static NSString *tingReuse = @"tingReuse";
        TingCell *tingCell = [tableView dequeueReusableCellWithIdentifier:tingReuse];
        if (!tingCell) {
            tingCell = [[TingCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:tingReuse];
        }
        DataModel *model = self.dataArr[indexPath.row];
        tingCell.model = model;
        
        tingCell.selectionStyle = UITableViewCellSelectionStyleNone;

        return tingCell;
        
    } else if ([[self.dataArr[indexPath.row] Type] isEqualToNumber:@3] || [[self.dataArr[indexPath.row] Type] isEqualToNumber:@7] || [[self.dataArr[indexPath.row] Type] isEqualToNumber:@11] || [[self.dataArr[indexPath.row] Type] isEqualToNumber:@27] || [[self.dataArr[indexPath.row] Type] isEqualToNumber:@29]) {
        
        static NSString *topicReuse = @"topicReuse";
        TopCell *topicCell = [tableView dequeueReusableCellWithIdentifier:topicReuse];
        if (!topicCell) {
            topicCell = [[TopCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:topicReuse];
        }
        
        DataModel *model = self.dataArr[indexPath.row];
        topicCell.model = model;
        topicCell.selectionStyle = UITableViewCellSelectionStyleNone;

        return topicCell;
        
    }else if ([[self.dataArr[indexPath.row] Type] isEqualToNumber:@5]) {
        static NSString *musicReuse = @"musicReuse";
        MusicCell *musicCell = [tableView dequeueReusableCellWithIdentifier:musicReuse];
        if (!musicCell) {
            musicCell = [[MusicCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:musicReuse];
        }
        DataModel *model = self.dataArr[indexPath.row];
        musicCell.model = model;
        musicCell.selectionStyle = UITableViewCellSelectionStyleNone;

        return musicCell;
        
    }else {
        static NSString *timelineReuse = @"timelineReuse";
        TimeLineCell *timelineCell = [tableView dequeueReusableCellWithIdentifier:timelineReuse];
        if (!timelineCell) {
            timelineCell = [[TimeLineCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:timelineReuse];
        }
        
        DataModel *model = self.dataArr[indexPath.row];
        timelineCell.model = model;
        timelineCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return timelineCell;
        
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DataModel *model = self.dataArr[indexPath.row];
    
    if ([model.Type  isEqual: @2]) {
        NSArray *musicArr = [NSArray array];
        musicArr = [RadioModel baseModelByArr:model.playList];
        NSInteger pushnum = 0;
        for (NSInteger i = 0; i < musicArr.count; i ++) {
            if ([model.title isEqualToString: [musicArr[i] title]]) {
                pushnum = i;
                break;
            }
        }
        RadioplayViewController *playVC = [[RadioplayViewController alloc]init];
        [RadioSavemodel shareSingleton].playlistArr = [NSMutableArray arrayWithArray:musicArr];
        [RadioSavemodel shareSingleton].playNumber = pushnum;
        [self.navigationController pushViewController:playVC animated:YES];
        
    }else{
        [ShowMytext showHUDloadView:SV];
        NSString *homePageSecDataUrl = @"http://api2.pianke.me/article/info";
        NSDictionary *para = @{@"auth":@"", @"client":@"1", @"contentid":[NSString stringWithFormat:@"%@", model.Id], @"deviceid":@"55887AC1-1871-4EAF-BC9F-648F8A10EE3D", @"version":@"3.0.6"};
    [DyAFnetWorking POSTAfnNetworkingWithUrl:homePageSecDataUrl WithParameters:para Block:^(id result) {
 
        WebView *webVC = [[WebView alloc]init];
        webVC.url = result[@"data"][@"shareinfo"][@"url"];
        webVC.tittle = result[@"data"][@"shareinfo"][@"title"] ;
        [self.navigationController pushViewController:webVC animated:YES];
        [ShowMytext hiddHUDloadView];
    }];
    }

}

/**
 *  创建右边用户按钮
 */
- (void)addRightButtonItem{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"yonghu1"] style:UIBarButtonItemStylePlain target:self action:@selector(presentRightMenuViewController:)];
    [self.navigationItem.rightBarButtonItem setTintColor:BUTTONCOLOR];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
